import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Popconfirm} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import {TableListItem} from './data.d';
import {save, remove, batchRemove, list, update, updateStatus} from './service';
import {AuthConsumer} from '@/utils/authContent'

/**
 * 添加
 * @param fields
 */
const handleSave = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    // console.log(fields)
    const data = await save({...fields});
    hide();
    if (data.code === 1) {
      message.success('添加成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('添加失败,请重试');
    return false;
  }
  message.error('添加失败,请重试');
  return false;
};

/**
 * 更新
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('更新添加');
  try {
    const data = await update({...fields});
    hide();
    if (data.code === 1) {
      message.success('更新成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('更新失败,请重试');
    return false;
  }
  message.error('更新失败,请重试');
  return false;
};


/**
 * 删除
 * @param record
 */
const handleRemove = async (record: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    const data = await remove(record.id);
    hide();
    if (data.code === 1) {
      message.success('删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
  message.error('删除失败，请重试');
  return false;
};

/**
 *  批量删除
 * @param selectedRows
 */
const handleBatchRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在批量删除');
  if (!selectedRows) return true;
  try {
    const ids = new Array();
    selectedRows.forEach((row: TableListItem) => {
      ids.push(row.id);
    })
    const data = await batchRemove(ids);
    hide();
    if (data.code === 1) {
      message.success('批量删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('批量删除失败，请重试');
    return false;
  }
  message.error('批量删除失败，请重试');
  return false;
};


/**
 * 更新状态
 *
 * @param id
 * @param jobStatus
 */
const handleUpdateStatus = async (id: number, jobStatus: number) => {
  const hide = message.loading('正在更新状态');
  try {
    const data = await updateStatus(id, jobStatus);
    hide();
    if (data.code === 1) {
      message.success('更新状态成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('更新状态失败，请重试');
    return false;
  }
  message.error('更新状态失败，请重试');
  return false;
};


const JobTaskTableList: React.FC<{}> = () => {
  // 创建Model可见性
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  // 更新Model可见性
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  // 设置更新表单值
  const [updateFormValues, setUpdateFormValues] = useState({});
  // 通过actionRef进行表单刷新
  const actionRef = useRef<ActionType>();
  //  选择行数据的状态
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  // 删除确认按钮
  const onRemoveConfirm = async (record: TableListItem) => {
    await handleRemove(record);
    actionRef.current?.reloadAndRest?.();
  }

  // 表头
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      valueType: 'textarea',
      hideInForm: true,
      align: "center",
    },
    {
      title: '任务名称',
      dataIndex: 'jobName',
      valueType: 'text',
      copyable: true,
      align: "center",
    },
    {
      title: '任务分组',
      dataIndex: 'jobGroup',
      valueType: 'text',
      align: "center",
    },
    {
      title: '全限定名',
      dataIndex: 'beanClass',
      hideInSearch: true,
      valueType: 'text',
      align: "center",
    },
    {
      title: 'cron表达式',
      dataIndex: 'cronExpression',
      valueType: 'text',
      hideInSearch: true,
      align: "center",
    },
    {
      title: '任务参数',
      dataIndex: 'jobParams',
      ellipsis: true,
      copyable: true,
      hideInSearch: true,
      valueType: 'text',
      align: "center",
    },
    {
      title: '下一次执行时间',
      dataIndex: 'nextExecuteDate',
      valueType: 'text',
      hideInSearch: true,
      align: "center",
    },
    {
      title: '状态',
      dataIndex: 'jobStatus',
      align: "center",
      valueEnum: {
        0: {text: '暂停', status: 'Default'},
        1: {text: '启用', status: 'Success'},
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: "center",
      render: (_, record) => (
        <>
          <AuthConsumer name={'tool:jobTask:update'}>
            <a onClick={() => {
              handleUpdateModalVisible(true);
              setUpdateFormValues(record);
            }}
            >修改</a>
          </AuthConsumer>
          <AuthConsumer name={'tool:jobTask:updateStatus'}>
            <Divider type="vertical"/>
            <Popconfirm
              title={record.jobStatus === 0 ? '确认需要启用' : '确认需要暂停'}
              okText="确定"
              cancelText="取消"
              onConfirm={async () =>{
                await handleUpdateStatus(record.id, (record.jobStatus === 0 ? 1 : 0))
                actionRef.current?.reloadAndRest?.();
              } }
            >
              <a href="#">{record.jobStatus === 0 ? '启用' : '暂停'}</a>
            </Popconfirm>
          </AuthConsumer>
          <AuthConsumer name={'tool:jobTask:remove'}>
            <Divider type="vertical"/>
            <Popconfirm
              title="确认需要删除"
              okText="确定"
              cancelText="取消"
              onConfirm={() => onRemoveConfirm(record)}
            >
              <a href="#">删除</a>
            </Popconfirm>
          </AuthConsumer>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      {/* 表格 */}
      <ProTable<TableListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <AuthConsumer name={'tool:jobTask:save'}>
            <Button type="primary" onClick={() => handleModalVisible(true)}>
              <PlusOutlined/> 添加
            </Button>
          </AuthConsumer>,
        ]}
        // request = {async (params, sorter, filter) => {
        request={async (params) => {
          console.log(params)
          const data = await list({...params});
          if (data.code === 1) {
            return {
              data: data.data.rows,
              // success请返回true，不然table会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: data.data.total,
            };
          }
          return {
            data: [],
            success: true,
            total: 0,
          }
        }
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />

      {/* 选择数据的状态 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <AuthConsumer name={'tool:jobTask:batchRemove'}>
            <Button danger type={"primary"}
                    onClick={async () => {
                      await handleBatchRemove(selectedRowsState);
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }}
            >
              批量删除
            </Button>
          </AuthConsumer>
        </FooterToolbar>
      )}

      {/* 创建表单 */}
      <CreateForm
        handleModalVisible={handleModalVisible}
        modalVisible={createModalVisible}
        handleSave={handleSave}
        actionRef={actionRef}
      ></CreateForm>

      {/* 更新表单 */}
      <UpdateForm
        updateModalVisible={updateModalVisible}
        handleUpdateModalVisible={handleUpdateModalVisible}
        updateFormValues={updateFormValues}
        handleUpdate={handleUpdate}
        actionRef={actionRef}
      ></UpdateForm>


    </PageContainer>
  );
};

export default JobTaskTableList;
